//
//  CityTableViewController.m
//  OneDay
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 oneDay. All rights reserved.
//

#import "CityTableViewController.h"
#import "CityTableViewCell.h"
#import "CityRecentlyTableViewCell.h"
#import "CityTViewController.h"

@interface CityTableViewController ()<MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) NSMutableArray *cityDataArray;
@property (nonatomic, strong) NSMutableArray *cityStyleDataArray;

@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;

@end

@implementation CityTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"城市列表";
    self.view.backgroundColor = [UIColor whiteColor];
    // 没有数据的时候为白色，没有线条
    self.tableView.separatorStyle = NO;
    // 开始加载动画
    [self addIndicatorView];
    [_indicatorView startAnimating];
    
    [self requestCityDataWithUrl:kCityUrl block:^{
        [self.tableView reloadData];
        [_indicatorView stopAnimating];
    }];
    
    // 添加返回按钮
    UIBarButtonItem *leftB = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-reply-3.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBar:)];
    self.navigationItem.leftBarButtonItem = leftB;
}

// 添加返回按钮
- (void)backBar:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 添加加载等待动画
- (void)addIndicatorView
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.center = self.view.center;
    _indicatorView.delegate = self;
    
    _indicatorView.numberOfCircles = 5; // 圆点个数
    _indicatorView.internalSpacing = 5; // 圆点之间的距离
    _indicatorView.radius = 6; // 圆点半径
    //    _indicatorView.delay = 0;
    
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}

#pragma mark - 加载等待动画的代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
            return [UIColor redColor];
            break;
        case 1:
            return [UIColor magentaColor];
            break;
        case 2:
            return [UIColor orangeColor];
            break;
        case 3:
            return [UIColor purpleColor];
            break;
        default:
            return [UIColor yellowColor];
            break;;
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cityStyleDataArray.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 0;
    }else{
        NSMutableArray *array = self.cityDataArray[section - 1];
        return array.count;
    }
}
// cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 300;
    }else{
        return 50;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        CityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cityCell"];
        if (cell == nil) {
            cell = [[CityTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cityCell"];
        }
        NSMutableArray *array = self.cityDataArray[indexPath.section];
        if (array.count != 0) {
            for (int i = 0; i < 15; i++) {
                CityModel *model = array[i];
                UIButton *button = (UIButton *)[cell viewWithTag:1000 + i];
                [button setTitle:model.city_name forState:(UIControlStateNormal)];
                [button addTarget:self action:@selector(cityButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
            }
        }
        return cell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"tableViewCell"];
        }
        NSMutableArray *allArray = self.cityDataArray[indexPath.section - 1];
        if (allArray.count > 0) {
            CityModel *model = allArray[indexPath.row];
            cell.textLabel.text = model.city_name;
        }
        return cell;
    }
}
// 添加表头标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"热门城市";
    }else if (section == 1){
        return @"全部城市";
    }else{
        NSString *str = self.cityStyleDataArray[section - 1];
        return str;
    }
}
// 右边的分区索引
- (NSMutableArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.cityStyleDataArray;
}
// cell跳转方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section != 0 && indexPath.section != 1) {
        CityTViewController *cityTVC = [[CityTViewController alloc] init];
        
        NSMutableArray *allArray = self.cityDataArray[indexPath.section - 1];
        if (allArray.count > 0) {
            CityModel *model = allArray[indexPath.row];
            cityTVC.needID = model.city_id;
        }
        [self.navigationController pushViewController:cityTVC animated:YES];
    }else{
        NSLog(@"我不跳转");
    }
}


#pragma mark -- 热门城市button点击方法
- (void)cityButtonAction:(UIButton *)sender
{
    NSMutableArray *array = self.cityDataArray[0];
    CityModel *model = array[sender.tag - 1000];
    CityTViewController *cityTVC = [[CityTViewController alloc] init];
    cityTVC.needID = model.city_id;
    [self.navigationController pushViewController:cityTVC animated:YES];
}

#pragma mark -- 请求数据
- (void)requestCityDataWithUrl:(NSString *)url block:(void(^)(void))block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [request setHTTPMethod:@"GET"];
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data == nil) {
                return ;
            }
            
            NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = rootDic[@"result"];
            // 取出result_count
            //NSInteger result_count = (NSInteger)rootDic[@"result_count"];
            self.cityDataArray = [NSMutableArray array];
            self.cityStyleDataArray = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                // 将表头内容添加进数组
                NSString *string = dic[@"begin_key"];
                if ([string isEqualToString:@"hot"]) {
                    string = @"热";
                }
                [self.cityStyleDataArray addObject:string];
                // 取出城市数据
                NSArray *cityArray = dic[@"city_list"];
                // 声明一个数组，装解析出来的每个分组的城市数据
                NSMutableArray *tempCityArray = [NSMutableArray array];
                for (NSDictionary *tempDic in cityArray) {
                    CityModel *model = [[CityModel alloc] init];
                    [model setValuesForKeysWithDictionary:tempDic];
                    [tempCityArray addObject:model];
                }
                // 将存有每个分组城市数据的数组装进 self.cityDataArray
                [self.cityDataArray addObject:tempCityArray];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }];
        [dataTask resume];
    });
}

#pragma mark -- 隐藏tabBar
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
